package com.zhiyou100.action;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou100.entity.Rect;
import com.zhiyou100.service.RectService;
import com.zhiyou100.util.object.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 房租 action
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-01 10:02
 */
@Controller
@RequestMapping("/rect")
public class RectAction {
    @Autowired
    private RectService service;

    @RequestMapping("/list.action")
    public String listHouses(Model model,
                             @RequestParam(defaultValue = "1",  value = "pageNo") Integer pageNo
    ) {
        // 每页显示的记录数
        int pageSize = 10;

        // 分页查询
        PageHelper.startPage(pageNo, pageSize);

        // 获取所有的信息
        final List<Rect> list = service.list();

        // 使用 PageInfo<Rect> 结果进行封装

        final PageInfo<Rect> pageInfo = new PageInfo<>(list);

        model.addAttribute("pageInfo", pageInfo);

        return "view/rect/list";
    }

    @RequestMapping("/getOne.action")
    public String getOneByHid(Integer id, String method, Model model) {
        final Rect rect = service.selectOne(id);
        if (rect != null) {
            // 有，放入区域中，跳转 到 详情页面
            if (method == null || method.trim().length() == 0) {
                // 跳转到 view/rect/detail
                model.addAttribute("rect", rect);
                return "view/rect/detail";
            } else {
                // 跳转到更新界面
                model.addAttribute("rect", rect);
                return "view/rect/update";
            }

        } else {
            // 没有，返回列表
            return "view/rect/list";
        }
    }

    @RequestMapping("/insertOne.action")
    public String insertOne(Rect rect) {

        String id = "rid";
        String addTime = "rtime";
        if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(rect, id, addTime)) {
            // lid 和  laddtime 字段为空，合法
            // 设置时间
            rect.setRtime(new Date());
            service.insertOne(rect);
        }

        return "/view/rect/list";
    }

    @RequestMapping("/updateOne.action")
    public String updateOneByCid(Rect rect) {

        String addTime = "rtime";
        if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(rect, addTime)) {
            // laddtime 字段为空，合法,设置添加时间
            rect.setRtime(new Date());

            service.updateOne(rect);
        }

        return "/view/rect/list";
    }


    @RequestMapping("/deleteOne.action")
    public String deleteOneByHid(Integer id) {
        if (id != null) {
            service.deleteOne(id);
        }
        return "view/rect/list";
    }

}
